import type { UserInfoFace } from "@/types/user";
import type { SendMsgType } from "@/utils/sendMsg";
function generateArray() {
  let arrGenerate = [];
  for (var i = 0; i < 26; i++) {
    var letter = String.fromCharCode(97 + i);
    arrGenerate.push(letter);
  }
  return arrGenerate;
}

const zimubiao = generateArray();

interface QsFace {
  label: string;
  user: string;
  value: 1 | 2;
  userName: string;
}

class WuziqiClass {
  rows: number;
  maps: number[][];
  active: number;
  index: number;
  status: number;
  id?: string;
  qsList: QsFace[];
  isUserStatus?: boolean;
  historyList: number[][];
  constructor() {
    this.rows = 15; // 棋盘的数量
    this.maps = []; // 棋盘
    this.active = 1; //  当前下棋的棋子 1为黑 2为白  黑先行
    this.index = 0; // 当前的步数
    this.status = 1; // 状态 1、等待开始 2、开始了 3、结束
    this.isUserStatus = true; // 是否是用户模式，用户模式需要棋手就位
    this.historyList = []
    this.qsList = [
      {
        label: "黑棋",
        user: "",
        value: 1,
        userName: "",
      },
      {
        label: "白棋",
        user: "",
        value: 2,
        userName: "",
      },
    ];
  }
  /**
   * 如果为正在下棋，则所有的文字消息走下此方法
   * @param msg
   */
  ai(msg: string, user: UserInfoFace, sendMsg: SendMsgType) {
    const ovwuziqiArr = ["结束下棋", "不下了", "不想下了"];
    const hqArr = ["悔棋", "下错了"];
    const cmdVal = msg.includes("黑棋") ? 1 : 2;
    if (msg.includes("黑棋") || msg.includes("白棋")) {
      this.updateQs(cmdVal, user);
      const tips = `${user.userName}已申请执${cmdVal == 1 ? "黑棋" : "白棋"}`;
      sendMsg.sendWzqSystem(tips);
      sendMsg.sendWzqQs(this.qsList);
    } else if (ovwuziqiArr.includes(msg)) {
      const isTrue = ovwuziqiArr.some((v) => msg.includes(v));
      if (isTrue) {
        sendMsg.broadcast({
          qipu: this.maps,
          type: "wuziqi",
          status: "over",
          msg: "下棋结束，棋谱如下",
        });
        this.close();
      }
    } else {
      /**
       * 悔棋
       */
      const isTrue = hqArr.some((v) => msg.includes(v));
      if (isTrue) {
        // let size = 1;
        // let result = msg.replace(/[^0-9]/g, "");
        // if (size && +result < 10 && +result != 0) {
        //   size = +result;
        // }
        const delData = this.huiqi();
        if (delData) {
          const [x, y] = delData;
          sendMsg.broadcast({
            type: "wuziqi",
            status: "return",
            msg: zimubiao[x] + y,
          });
        }
      } else {
        this.playMsg(msg, user, sendMsg);
      }
    }
  }
  playMsg(msg: string, user: UserInfoFace, sendMsg: SendMsgType) {
    const zimu = msg.replace(/[^a-zA-Z]+/, "");
    const y = msg.replace(/[^0-9]+/, "");

    const x = zimubiao.findIndex(
      (v) => v.toLocaleLowerCase() == zimu.toLocaleLowerCase()
    );

    if (x > -1 && y) {
      const player = this.active;
      const qname = player == 1 ? "黑棋" : "白棋";
      this.play(x, +y, user.userId)
        .then((res: any) => {
          sendMsg.broadcast({
            type: "wuziqi",
            status: "play",
            msg: `${zimu}${y}`,
            player,
          });
          if (res.status) {
            const newmsg = ` 当前已经胜利，胜利者是：${user.userName}的${qname}。\r您可以和我说《开始下五子棋》，继续开始下棋'`;
            sendMsg.sendWzqSystem(newmsg);
            sendMsg.broadcast({
              qipu: this.maps,
              type: "wuziqi",
              status: "over",
              msg: "下棋结束，棋谱如下",
            });
            this.close();
          }
        })
        .catch((err: string) => {
          sendMsg.sendWzqSystem(err);
        });
    }
  }
  updateQs(qswz: any, userInfos: UserInfoFace) {
    const wz = Number(qswz) - 1;
    if (wz == 0 || wz == 1) {
      this.qsList[wz].user = userInfos.userId;
      this.qsList[wz].userName = userInfos.userName;
    }
  }

  /**
   * 开始下棋
   */
  start() {
    if (this.active != 2) {
      this.reset();
      this.status = 2;
      this.historyList = [];
      this.id =
        new Date().getTime().toString() +
        Math.floor(Math.random() * 100).toString();
    }
  }
  huiqi() {
    const length = this.historyList.length - 1;
    const delData = this.historyList.pop();
    if (delData) {
      const [x, y] = delData;
      this.maps[x][y] = 0;
    }
    if (length % 2 == 0) {
      this.active = 1;
    } else {
      this.active = 2;
    }
    return delData;
  }
  close() {
    this.status = 3;
    this.active = 1;
    this.index = 0;
    this.initMaps();
  }
  /**
   * 重置
   */
  reset() {
    this.active = 1;
    this.index = 0;
    this.initMaps();
    this.status = 1;
    this.historyList = [];
  }
  /**
   * 初始化棋盘
   */
  initMaps() {
    for (var row = 0; row < this.rows; row++) {
      this.maps[row] = [];
      for (var low = 0; low <= this.rows; low++) {
        this.maps[row][low] = 0;
      }
    }
  }
  /**
   * 是否可以移动
   * @param x
   * @param y
   * @returns
   */
  isValidMove(x: number, y: number) {
    return x >= 0 && x < this.rows && y >= 0 && y < this.rows;
  }
  /**
   * 是否为空
   * @param x
   * @param y
   * @returns
   */
  isEmptyCell(x: number, y: number) {
    return this.maps[x][y] === 0;
  }
  getStatus(x: number, y: number) {
    if (!this.maps[x]) return undefined;
    return this.maps[x][y];
  }
  /**
   * 检查
   * @param row
   * @param col
   * @param player
   * @returns
   */
  hasFiveInRow(row: number, col: number, player: number) {
    // 检查水平方向
    var count = 0;
    for (var i = col - 4; i <= col + 4; i++) {
      if (this.isValidMove(row, i) && this.maps[row][i] === player) {
        count++;
        if (count === 5) {
          return true;
        }
      } else {
        count = 0;
      }
    }
    // 检查垂直方向
    count = 0;
    for (var i = row - 4; i <= row + 4; i++) {
      if (this.isValidMove(i, col) && this.maps[i][col] === player) {
        count++;
        if (count === 5) {
          return true;
        }
      } else {
        count = 0;
      }
    }
    // 检查正斜线方向
    count = 0;
    for (var i = -4; i <= 4; i++) {
      if (
        this.isValidMove(row + i, col + i) &&
        this.maps[row + i][col + i] === player
      ) {
        count++;
        if (count === 5) {
          return true;
        }
      } else {
        count = 0;
      }
    }
    // 检查反斜线方向
    count = 0;
    for (var i = -4; i <= 4; i++) {
      if (
        this.isValidMove(row - i, col + i) &&
        this.maps[row - i][col + i] === player
      ) {
        count++;
        if (count === 5) {
          return true;
        }
      } else {
        count = 0;
      }
    }
    return false;
  }
  getActiveUser() {
    return this.qsList.find((v) => v.value == this.active);
  }
  isJiuwei() {
    return this.qsList.some((v) => !v.user);
  }
  isUser(userId: string) {
    const activeUserData = this.getActiveUser();
    return activeUserData && activeUserData.user == userId;
  }
  play(x: number, y: number, userId: string) {
    return new Promise((resolve, reject) => {
      // 如果开启了 棋手模式，则需要棋手就位

      if (this.isUserStatus) {
        if (this.isJiuwei()) {
          reject(`当前棋手尚未就位，你可以说我要下黑棋，进行下棋`);
          return;
        } else if (!this.isUser(userId)) {
          const activeUserData = this.getActiveUser();
          reject(
            `当前是${activeUserData.user}的${activeUserData.value == 1 ? "黑棋" : "白棋"
            }下棋，请等待，若无法下棋,您可以说，我要下黑棋`
          );
          return;
        }
      }
      if (this.isValidMove(x, y) && this.isEmptyCell(x, y)) {
        this.maps[x][y] = this.active;
        this.historyList.push([x, y]);
        const isTrue = this.hasFiveInRow(x, y, this.active);


        this.index++;
        resolve({
          status: isTrue,
          user: this.active,
        });
        this.active = this.active === 1 ? 2 : 1;

      } else {
        reject('位置错误');
      }
    });
  }
}

export default WuziqiClass;
